package com.ding.dailyup.controller;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ding.dailyup.constant.HotIndustryDayTypeEnum;
import com.ding.dailyup.entity.JsonResult;
import com.ding.dailyup.entity.response.HotIndustryItemResp;
import com.ding.dailyup.entity.response.HotIndustryResp;
import com.ding.dailyup.service.HotIndustryService;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/market")
@Api(tags = "行情数据")
public class MarketController {

	@Autowired
	private HotIndustryService hotIndustryService;

	@GetMapping(value = "/hot/industry")
	@ApiOperation(value = "热点板块")
	public JsonResult<HotIndustryResp> getHotIndustry(
			@RequestParam(value = "dayType") int dailyDuration) {
		JSONArray hotIndustry = hotIndustryService
				.getHotIndustry(dailyDuration);
		HotIndustryResp hotIndustryResp = new HotIndustryResp();
		hotIndustryResp.setIndustry(this.wrapRes(hotIndustry, dailyDuration));
		return JsonResult.succResult(hotIndustryResp);
	}

	private List<HotIndustryItemResp> wrapRes(JSONArray hotIndustry,
			int dayType) {
		List<HotIndustryItemResp> rs = Lists.newArrayList();
		for (int i = 0; i < hotIndustry.size(); i++) {
			HotIndustryItemResp item = new HotIndustryItemResp();
			JSONObject js = hotIndustry.getJSONObject(i);
			item.setIndustryName(js.getString("f14"));
			if (dayType == HotIndustryDayTypeEnum.TODAY.getDayType()) {
				item.setZd(js.getString("f3"));
				item.setHotStock(js.getString("f204"));
			} else if (dayType == HotIndustryDayTypeEnum.FIVEDAY.getDayType()) {
				item.setZd(js.getString("f109"));
				item.setHotStock(js.getString("f257"));
			} else if (dayType == HotIndustryDayTypeEnum.TENDAY.getDayType()) {
				item.setZd(js.getString("f160"));
				item.setHotStock(js.getString("f260"));
			} else {
				continue;
			}
			rs.add(item);
		}
		return rs.stream().sorted((o1, o2) -> Double.parseDouble(o1.getZd())
				- Double.parseDouble(o2.getZd()) < 0 ? 1 : -1).collect(Collectors.toList());
	}
}
